function add2Table(s, main, p1, p2)
{
  var div = document.getElementById(main);
  var parent = document.createElement('div');
  parent.id = p1 + s;
  parent.setAttribute('domain', s);
  div.appendChild(parent);

  var element = document.createElement('input');
  element.type = "checkbox";
  element.id = p2 + s;
  element.onclick = checkboxClicked;
  
  var label = document.createElement('label');
  label.setAttribute('for', element.id);
  label.innerHTML = s;
  
  parent.appendChild(element);
  parent.appendChild(label);
}

function add2TableTo(s)
{
  add2Table(s, 'main1', 'p_', 'c_');
}

function add2TableFrom(s)
{
  add2Table(s, 'main2', 'h_', 's_');
}

var counterTo = 0;
var counterFrom = 0;

function checkboxClicked(e)
{
  if(this.id.substr(0, 1) == 'c')
  {
    if(this.checked) counterTo++;
    else counterTo--;
  }
  else
  {
    if(this.checked) counterFrom++;
    else counterFrom--;
  }
  document.getElementById('removeTo').disabled = (counterTo == 0);
  document.getElementById('removeFrom').disabled = (counterFrom == 0);
}

function readStorage()
{
  var a = chrome.extension.getBackgroundPage().whiteListTo;
  for(i = 0; i < a.length; i++)
  {
    add2TableTo(a[i]);
  }
  var b = chrome.extension.getBackgroundPage().whiteListFrom;
  for(i = 0; i < b.length; i++)
  {
    add2TableFrom(b[i]);
  }
}

function remove(main, prefix)
{
  var div = document.getElementById(main);
  var child = div.firstChild;
  var a = [];
  while(child)
  {
    if(child.tagName && child.tagName.toLowerCase() == 'div')
    {
      if(child.className == undefined || (child.className.toLowerCase() != 'header'))
      {
        var d = child.getAttribute('domain');
        console.log(d);
        var check = document.getElementById(prefix + d);
        if(check.checked)
        {
          check.checked = false;
          child.style.display = 'none';
        }
        else
        {
          a.push(d);
        }
      }
    }
    child = child.nextSibling;
  }
  return a;
}

function removeTo()
{
  chrome.extension.getBackgroundPage().replaceWhiteListTo(remove('main1', 'c_'));
}

function removeFrom()
{
  chrome.extension.getBackgroundPage().replaceWhiteListFrom(remove('main2', 's_'));
}

document.addEventListener('DOMContentLoaded', function()
{
  readStorage();
  document.getElementById('removeTo').addEventListener('click', removeTo);
  document.getElementById('removeFrom').addEventListener('click', removeFrom);
});
